package com.chucang.shucang.common.base.page;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chucang.shucang.common.base.query.Query;
import com.chucang.shucang.common.base.xss.SQLFilter;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/3 18:36
 * @description mybatis-plus分页工具
 */
public class PageQuery<T> {

    private static final String ASC = "asc";

    public IPage<T> getPage(Query query) {
        return this.getPage(query, null, false);
    }

    public IPage<T> getPage(Query query, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (query.getPage() != null) {
            curPage = query.getPage();
        }
        if (query.getLimit() != null) {
            limit = query.getLimit();
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = SQLFilter.sqlInject(query.getOrderField());
        String order = query.getOrder();


        //前端字段排序
        if (CharSequenceUtil.isNotEmpty(orderField) && CharSequenceUtil.isNotEmpty(order)) {
            if (ASC.equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if (CharSequenceUtil.isBlank(defaultOrderField)) {
            return page;
        }

        //默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}
